package com.example.test_20211117_dom4j;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @program: demo
 * @description: do4j解析xml
 * @author: liulei
 * @create: 2021-11-17 14:31
 **/
public class Dom4jXml {

    public static void dealXml(){
        SAXReader reader = new SAXReader();

        try {
            Document read = reader.read("d:/book.xml");
            Element rootElement = read.getRootElement();
            Iterator<Element> elementIterator2 = rootElement.elementIterator();
            List<Book> bookList = new ArrayList<>();
            while (elementIterator2.hasNext()){
                JSONObject jsonObject = (JSONObject)JSONObject.toJSON(new Book());
                Element next = elementIterator2.next();
                String id = next.attributeValue("id");
                System.out.println("id="+id);
                List<Attribute> attributes = next.attributes();
                for (Attribute attribute :attributes){
                    String name = attribute.getName();
                    String value = attribute.getValue();
                    System.out.println("name="+name+" value="+value);
                    jsonObject.put(name,value);
                }
                Iterator<Element> elementIterator = next.elementIterator();
                while (elementIterator.hasNext()){
                    Element next1 = elementIterator.next();
                    System.out.println("name="+next1.getName()+" value="+next1.getStringValue());
                    jsonObject.put(next1.getName(),next1.getStringValue());
                }
                Book book = jsonObject.toJavaObject(Book.class);
//                Book book1 = JSON.toJavaObject(jsonObject, Book.class);
                bookList.add(book);
            }
            System.out.println("list="+bookList);
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        dealXml();
    }
}
